//导入express
const express = require('express');

//声明中间件
const checkTokenMiddleware = require('../../middlewares/checkTokenMiddleware');

const router = express.Router();

//导入moment-timezone
const moment = require('moment-timezone');

//设置时区
moment.tz.setDefault("Asia/Shanghai")

const AccountModel = require('../../models/AccountModel');





// 记账本列表
router.get('/account', checkTokenMiddleware, function (req, res, next) {
    //响应成功的提示
    //获取所有的账单信息
    // let accounts = db.get('accounts').value();
    AccountModel.find().sort({ time: -1 }).exec().then((data) => {
      // console.log(data);
      //响应成功的提示
      res.json({
        code: '0000',
        msg: '读取成功',
        data: data
      })

    }).catch(() => {
      res.json({
        code: '1001',
        msg: '读取失败',
        data: null
      })
    });

});



//新增记录
router.post('/account', checkTokenMiddleware, (req, res) => {
  //插入数据库
  AccountModel.create({
    ...req.body,
    // 修改time属性的值
    time: moment(req.body.time).toDate()
  }).then((data) => {   //改成promise语法
    //成功提醒
    res.json({
      code: '0000',
      msg: '添加成功',
      data: data
    });
  }).catch((err) => {
    res.json({
      code: '1002',
      msg: '添加失败',
      data: null
    })
  });


});


//删除记录
router.delete('/account/:id', checkTokenMiddleware, (req, res) => {
  //获取params的id参数
  let id = req.params.id;
  //删除
  AccountModel.deleteOne({ _id: id }).then((data) => {
    //提醒
    res.json({
      code: "0000",
      msg: '删除成功',
      data: {}

    })
  }).catch((err) => {
    res.json({
      code: "1003",
      msg: '删除账单失败',
      data: null

    })
  });

});

//获取单个账单信息
router.get('/account/:id', checkTokenMiddleware, (req, res) => {
  //获取params的id参数
  let { id } = req.params;
  //查询数据库
  AccountModel.findById(id).then((data) => {
    res.json({
      code: "0000",
      msg: '读取成功',
      data: data
    });

  }).catch((err) => {
    res.json({
      code: "1004",
      msg: '读取失败',
      data: null

    })
  });

});


//更新账单接口
router.patch('/account/:id', checkTokenMiddleware, (req, res) => {
  //获取params的id参数
  let { id } = req.params;
  AccountModel.updateOne({ _id: id }, req.body).then((data) => {
    //再次查询数据库获取单条数据
    AccountModel.findById(id).then((data) => {
      res.json({
        code: "0000",
        msg: '更新成功',
        data: data
      });

    }).catch((err) => {
      res.json({
        code: "1004",
        msg: '读取失败',
        data: null

      })
    });
  }).catch((err) => {
    res.json({
      code: "1005",
      msg: '更新失败',
      data: null

    })
  });

})



module.exports = router;
